package com.example.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.project.common.Result;
import com.example.project.entity.Category;
import com.example.project.mapper.CategoryMapper;
import com.example.project.service.CategoryService;
import com.example.project.vo.CategoryTreeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    
    @Override
    public List<Category> getEnabledCategories() {
        return baseMapper.selectEnabledCategories();
    }
    
    @Override
    public List<CategoryTreeVO> getCategoryTree() {
        // 获取所有启用的分类
        List<Category> allCategories = this.getEnabledCategories();
        
        // 转换为TreeVO对象
        List<CategoryTreeVO> allTreeNodes = allCategories.stream()
                .map(this::convertToTreeVO)
                .collect(Collectors.toList());
        
        // 构建父子关系
        Map<Long, List<CategoryTreeVO>> parentMap = allTreeNodes.stream()
                .filter(node -> node.getLevel() == 2) // 只处理二级分类
                .collect(Collectors.groupingBy(node -> {
                    Category category = allCategories.stream()
                            .filter(c -> c.getId().equals(node.getId()))
                            .findFirst()
                            .orElse(null);
                    return category != null ? category.getParentId() : 0L;
                }));
        
        // 返回一级分类（包含子分类）
        return allTreeNodes.stream()
                .filter(node -> node.getLevel() == 1)
                .peek(node -> node.setChildren(parentMap.getOrDefault(node.getId(), new ArrayList<>())))
                .collect(Collectors.toList());
    }
    
    @Override
    public List<Category> getFirstLevelCategories() {
        return list(new LambdaQueryWrapper<Category>()
                .eq(Category::getLevel, 1)
                .eq(Category::getStatus, 1)
                .orderByAsc(Category::getSort));
    }
    
    @Override
    public List<Category> getSecondLevelCategories(Long parentId) {
        return list(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, parentId)
                .eq(Category::getLevel, 2)
                .eq(Category::getStatus, 1)
                .orderByAsc(Category::getSort));
    }
    
    @Override
    @Transactional
    public Result<?> addCategory(Category category) {
        // 参数校验
        if (category.getLevel() == null) {
            return Result.error("分类层级不能为空");
        }
        
        // 设置默认值
        category.setStatus(1);
        if (category.getSort() == null) {
            category.setSort(0);
        }
        
        // 检查父分类
        if (category.getLevel() == 2) {
            if (category.getParentId() == null) {
                return Result.error("二级分类必须指定父分类");
            }
            Category parent = getById(category.getParentId());
            if (parent == null || parent.getLevel() != 1) {
                return Result.error("父分类不存在或不是一级分类");
            }
        } else {
            category.setParentId(null);  // 一级分类的parentId设为null
        }
        
        save(category);
        return Result.success();
    }
    
    @Override
    @Transactional
    public Result<?> updateCategory(Category category) {
        Category existing = getById(category.getId());
        if (existing == null) {
            return Result.error("分类不存在");
        }
        
        // 不允许修改层级和父分类
        category.setLevel(existing.getLevel());
        category.setParentId(existing.getParentId());
        
        if (!updateById(category)) {
            return Result.error("更新失败");
        }
        return Result.success();
    }
    
    @Override
    @Transactional
    public Result<?> deleteCategory(Long id) {
        Category category = getById(id);
        if (category == null) {
            return Result.error("分类不存在");
        }
        
        // 检查是否有子分类
        if (category.getLevel() == 1) {
            long count = count(new LambdaQueryWrapper<Category>()
                    .eq(Category::getParentId, id));
            if (count > 0) {
                return Result.error("该分类下还有子分类，不能删除");
            }
        }
        
        // 检查分类下是否有商品
        int productCount = baseMapper.countProductsByCategory(id);
        if (productCount > 0) {
            return Result.error("该分类下还有商品，不能删除");
        }
        
        if (!removeById(id)) {
            return Result.error("删除失败");
        }
        return Result.success();
    }
    
    @Override
    @Transactional
    public Result<?> toggleStatus(Long id, Integer status) {
        Category category = getById(id);
        if (category == null) {
            return Result.error("分类不存在");
        }
        
        category.setStatus(status);
        if (!updateById(category)) {
            return Result.error("更新状态失败");
        }
        return Result.success();
    }
    
    @Override
    @Transactional
    public Result<?> updateSort(Long id, Integer sort) {
        Category category = getById(id);
        if (category == null) {
            return Result.error("分类不存在");
        }
        
        category.setSort(sort);
        if (!updateById(category)) {
            return Result.error("更新排序失败");
        }
        return Result.success();
    }
    
    // 将Category转换为CategoryTreeVO
    private CategoryTreeVO convertToTreeVO(Category category) {
        CategoryTreeVO vo = new CategoryTreeVO();
        BeanUtils.copyProperties(category, vo);
        return vo;
    }
} 